package com.epoint.mobileoa.tools;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;


/**
 * @author liyc
 * @time 2012-2-20 下午3:44:00
 * @annotation HTTP传输帮助类
 */

public class HttpUtil {

	/**
	 * 网络连接超时时间
	 */
	public static final int CONNECTION_TIME_OUT_TIME = 60 * 1000;

	/**
	 * 网络超时标示
	 */
	public static final String CONNECTION_TIME_OUT = "connection timed out";

	/**
	 * 请求成功常量
	 */
	public final static String RESPONSEINFO_SUCCESS = "<RESULT>responseinfo_success</RESULT>";

	/**
	 * 请求失败常量
	 */
	public final static String RESPONSEINFO_FAILURE = "<RESULT>responseinfo_failure</RESULT>";

	/**
	 * 无后台对于接口标示
	 */
	public final static String NO_SUCH_METHOD = "<ERR>NO_SUCH_METHOD</ERR>";

	/**
	 * 后台接口异常标示
	 */
	public final static String INTERFACE_ERR = "<ERR>INTERFACE_ERR</ERR>";

	public static String getHttpBack(String seamurl) {
		System.out.println("访问URL"+seamurl);
		String seamStr = "";
		seamurl = seamurl.replaceAll(" ", "%20");

		HttpClient httpClient = new DefaultHttpClient();

		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT,
				CONNECTION_TIME_OUT_TIME);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				CONNECTION_TIME_OUT_TIME);

		HttpGet get = new HttpGet(seamurl);
		try {
			HttpResponse httpResponse = httpClient.execute(get);
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				InputStream in = entity.getContent();
				GZIPInputStream gunzip = new GZIPInputStream(in);
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int n;
				while ((n = gunzip.read(buffer)) >= 0) {
					out.write(buffer, 0, n);
				}
				byte[] b = out.toByteArray();
				out.close();
				gunzip.close();
				in.close();
				seamStr = new String(b);
			} else {
				seamStr = CONNECTION_TIME_OUT;
			}
		} catch (Exception e) {
			e.printStackTrace();
			seamStr = CONNECTION_TIME_OUT;
		}
		return seamStr;
	}

	public static Bitmap getBitmapHttpBack(String seamurl) {
		Bitmap photo = null;
		seamurl = seamurl.replaceAll(" ", "%20");

		HttpClient httpClient = new DefaultHttpClient();

		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT,
				CONNECTION_TIME_OUT_TIME);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				CONNECTION_TIME_OUT_TIME);

		HttpGet get = new HttpGet(seamurl);
		try {
			HttpResponse httpResponse = httpClient.execute(get);
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				InputStream in = entity.getContent();
				// GZIPInputStream gunzip = new GZIPInputStream(in);
				// ByteArrayOutputStream out = new ByteArrayOutputStream();
				// byte[] buffer = new byte[1024];
				// int n;
				// int len=0;
				// while ((n = gunzip.read(buffer)) >= 0) {
				// len += n;
				// out.write(buffer, 0, n);
				// }
				// byte[] b = out.toByteArray();
				// out.close();
				// gunzip.close();
				// in.close();
				BufferedInputStream bis = new BufferedInputStream(in);
				photo = BitmapFactory.decodeStream(bis);

			} else {
				// seamStr = CONNECTION_TIME_OUT;
			}
		} catch (Exception e) {
			e.printStackTrace();
//			LogHelp.Log2SDInfo("无法连接到服务端：" + seamurl);
			// seamStr = CONNECTION_TIME_OUT;
		}
		return photo;
	}

	// ByteArrayOutputStream out = new ByteArrayOutputStream();
	// byte[] buffer = new byte[1024];
	// int n;
	// int len = 0;
	// while ((n = in.read(buffer)) >= 0) {
	// len = len + n;
	// out.write(buffer, 0, n);
	// }
	// byte[] b = out.toByteArray();
	// out.close();
	// // gunzip.close();
	// in.close();
	// photo = BitmapFactory.decodeByteArray(b, 0, len);
	public static String getHttpBackUnZip(String seamurl) throws Exception {
		String seamStr = "";
		seamurl = seamurl.replaceAll(" ", "%20");
		HttpGet get = new HttpGet(seamurl);
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT,
				CONNECTION_TIME_OUT_TIME);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				CONNECTION_TIME_OUT_TIME);
		try {
			HttpResponse httpResponse = httpClient.execute(get);
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				InputStream in = entity.getContent();
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int n;
				while ((n = in.read(buffer)) >= 0) {
					out.write(buffer, 0, n);
				}
				byte[] b = out.toByteArray();
				out.close();
				in.close();
				seamStr = new String(b);
			} else {
				seamStr = CONNECTION_TIME_OUT;
			}
		} catch (Exception e) {
			e.printStackTrace();
//			LogHelp.Log2SDInfo("无法连接到服务端:" + seamurl);
			seamStr = CONNECTION_TIME_OUT;
		}
		return seamStr;
	}

	/**
	 * 提交Post数据请求
	 * 
	 * @param actionUrl
	 *            请求URL
	 * @param params
	 *            提交文本信息，键值对
	 * @param files
	 *            提交的文件对象，键值对
	 * @return 后台响应数据
	 * @throws IOException
	 */
	public static String post(String actionUrl, Map<String, String> params,
			Map<String, File> files) throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(30 * 1000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);
		conn.setConnectTimeout(CONNECTION_TIME_OUT_TIME);
		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}
		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());
		outStream.write(sb.toString().getBytes());

		// 发送文件数据
		if (files != null&&files.size()>0)
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
						+ URLEncoder.encode(file.getKey(), "utf-8")
						+ "\""
						+ LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());
				Log.d("tracy", "sb1=" + sb1.toString());
				InputStream is = new FileInputStream(file.getValue());

				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}
				is.close();
				outStream.write(LINEND.getBytes());
			}

		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();

		String seamStr = "";
		// 得到响应码
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream in = conn.getInputStream();
			GZIPInputStream gunzip = new GZIPInputStream(in);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
			byte[] b = out.toByteArray();
			out.flush();
			out.close();
			gunzip.close();
			in.close();
			seamStr = new String(b);
		} else {
			seamStr = CONNECTION_TIME_OUT;
		}
		outStream.close();
		conn.disconnect();
		return seamStr;
	}
}
